package com.ruoyi.system.service.impl.smy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.LinkUrl;
import com.ruoyi.common.constant.OrderStatusEnum;
import com.ruoyi.common.constant.OrderType;
import com.ruoyi.common.core.domain.smy.MallMerchantPersonalInfo;
import com.ruoyi.common.core.domain.smy.MallOrder;
import com.ruoyi.common.core.domain.smy.MallOrderDetail;
import com.ruoyi.common.core.domain.smy.SecurityWebUser;
import com.ruoyi.common.dto.ResponseDto;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.system.mapper.smy.MallOrderMapper;
import com.ruoyi.system.service.smy.IMallMerchantPersonalInfoService;
import com.ruoyi.system.service.smy.IMallOrderDetailService;
import com.ruoyi.system.service.smy.IMallOrderService;
import com.ruoyi.system.service.smy.ISecurityWebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class MallOrderServiceImpl implements IMallOrderService {

	private static final Logger log = LoggerFactory.getLogger(MallOrderServiceImpl.class);

	@Resource
	private MallOrderMapper mallOrderMapper;

	@Resource
	private ISecurityWebUserService securityWebUserService;

	@Resource
	private IMallOrderDetailService orderDetailService;

	@Resource
	private IMallMerchantPersonalInfoService personalInfoService;

	/**
	 * 查询【请填写功能名称】
	 *
	 * @param id 【请填写功能名称】主键
	 * @return 【请填写功能名称】
	 */
	@Override
	public MallOrder selectMallOrderById(Long id) {
		return mallOrderMapper.selectMallOrderById(id);
	}

	/**
	 * 查询【请填写功能名称】列表
	 *
	 * @param mallOrder 【请填写功能名称】
	 * @return 【请填写功能名称】
	 */
	@Override
	public List<MallOrder> selectMallOrderList(MallOrder mallOrder) {
		return mallOrderMapper.selectMallOrderList(mallOrder);
	}

	/**
	 * 新增【请填写功能名称】
	 *
	 * @param mallOrder 【请填写功能名称】
	 * @return 结果
	 */
	@Override
	public int insertMallOrder(MallOrder mallOrder) {
		return mallOrderMapper.insertMallOrder(mallOrder);
	}

	/**
	 * 修改【请填写功能名称】
	 *
	 * @param mallOrder 【请填写功能名称】
	 * @return 结果
	 */
	@Override
	public int updateMallOrder(MallOrder mallOrder) {
		return mallOrderMapper.updateMallOrder(mallOrder);
	}

	/**
	 * 批量删除【请填写功能名称】
	 *
	 * @param ids 需要删除的【请填写功能名称】主键
	 * @return 结果
	 */
	@Override
	public int deleteMallOrderByIds(Long[] ids) {
		return mallOrderMapper.deleteMallOrderByIds(ids);
	}

	/**
	 * 删除【请填写功能名称】信息
	 *
	 * @param id 【请填写功能名称】主键
	 * @return 结果
	 */
	@Override
	public int deleteMallOrderById(Long id) {
		return mallOrderMapper.deleteMallOrderById(id);
	}

	@Override
	public List<MallOrder> selectMallOrderPage(MallOrder mallOrder) {
		return mallOrderMapper.selectMallOrderPage(mallOrder);
	}

	@Override
	public void cancelOrder(MallOrder mallOrder) {
		//凭券下单并且订单是未支付状态，直接修改状态为已取消
		if(NumberUtil.compare(OrderType.FREE_TICKET,mallOrder.getDistributorsource())==0
				&& NumberUtil.compare(Integer.parseInt(OrderStatusEnum.NO_PAY_ORDER.getStatusId()),mallOrder.getStatus())==0){
			mallOrder.setStatus(Integer.parseInt(OrderStatusEnum.SHOP_ORDER_CANCEL.getStatusId()));
			mallOrderMapper.updateMallOrder(mallOrder);
		}
	}

	@Override
	public void confirmOrder(String appBaseUrl, String microImageUrl, MallOrder mallOrder) {
		//凭券下单并且订单是未支付状态，修改状态为新订单
		if(NumberUtil.compare(OrderType.FREE_TICKET,mallOrder.getDistributorsource())==0
				&& NumberUtil.compare(Integer.parseInt(OrderStatusEnum.NO_PAY_ORDER.getStatusId()),mallOrder.getStatus())==0){
			shareOrderToAPP(mallOrder,appBaseUrl,microImageUrl);
			mallOrder.setStatus(Integer.parseInt(OrderStatusEnum.SHOP_ORDER_NEW.getStatusId()));
			mallOrderMapper.updateMallOrder(mallOrder);
		}
	}

	@Override
	public MallOrder getOrderDetail(Long id) {
		MallOrder mallOrder = mallOrderMapper.selectMallOrderById(id);
		if(Objects.nonNull(mallOrder)){
			MallOrderDetail queryDto = new MallOrderDetail();
			queryDto.setOrderId(mallOrder.getId());
			List<MallOrderDetail> orderDetailList = orderDetailService.selectMallOrderDetailList(queryDto);
			mallOrder.setOrderDetailList(orderDetailList);

			SecurityWebUser merchant = securityWebUserService.selectSecurityWebUserById(mallOrder.getMerchantId());
			MallMerchantPersonalInfo personalInfo = personalInfoService.selectMallMerchantPersonalInfoById(merchant.getMerchantpersonalinfoId());
			if(Objects.nonNull(personalInfo)){
				mallOrder.setMerchantName(personalInfo.getCookername());
				mallOrder.setMerchantPhone(merchant.getMobile());
			}
			SecurityWebUser member = securityWebUserService.selectSecurityWebUserById(mallOrder.getMemberId());
			if(Objects.nonNull(member)){
				mallOrder.setMemberName(member.getNickname());
				mallOrder.setMemberPhone(member.getMobile());
			}
		}
		return mallOrder;
	}

	/**
	 *  将订单同步到APP平台
	 * @Date 2022/10/20 9:57
	 * @author ZhanCheng.Li
	 * @param mallOrder
	 * @param appBaseUrl
	 * @param microImageUrl
	 */
	private void shareOrderToAPP(MallOrder mallOrder, String appBaseUrl, String microImageUrl) {
		Map<String, Object> orderMap = MapUtil.newHashMap();
		//商家信息
		SecurityWebUser merchant = securityWebUserService.selectSecurityWebUserById(mallOrder.getMerchantId());
		//买家信息
		SecurityWebUser member = securityWebUserService.selectSecurityWebUserById(mallOrder.getMemberId());
		if(Objects.nonNull(merchant)){
			orderMap.put("shopUserPhone", merchant.getMobile());
		}
		//设置送达信息
		if(StrUtil.equals("store",mallOrder.getDiningway())){
			orderMap.put("serviceOrderDeliveryContactName", mallOrder.getConcatname());
			orderMap.put("serviceOrderDeliveryContactNumber", mallOrder.getConcatphone());
			orderMap.put("serviceOrderDeliveryStandByMobile",member.getMobile());
		}else{
			orderMap.put("serviceOrderDeliveryContactName", mallOrder.getDeliveryname());
			orderMap.put("serviceOrderDeliveryContactNumber", mallOrder.getDeliverymobile());
			orderMap.put("serviceOrderDeliveryStandByMobile",mallOrder.getStandbymobile());
		}
		if(Objects.nonNull(mallOrder.getDeliverypca())){
			orderMap.put("serviceOrderDeliveryAddress", mallOrder.getDeliverypca()+ mallOrder.getDeliveryaddress());
		}
		if(Objects.isNull(mallOrder.getDeliverypca())){
			orderMap.put("serviceOrderDeliveryAddress", mallOrder.getDeliveryprovince() + mallOrder.getDeliverycity() + mallOrder.getDeliveryarea() + mallOrder.getDeliveryaddress());
		}
		if(Objects.nonNull(mallOrder.getDeliverylat())){
			orderMap.put("serviceOrderDeliveryAddressLat",mallOrder.getDeliverylat());
		}
		if(Objects.nonNull(mallOrder.getDeliverylon())){
			orderMap.put("serviceOrderDeliveryAddressLon",mallOrder.getDeliverylon());
		}
		orderMap.put("orderPrice", NumberUtil.round(mallOrder.getShopamount(), 2).doubleValue());

		orderMap.put("bookingDate", mallOrder.getBookingdate());
		orderMap.put("bookingTime", mallOrder.getBookingdatetime());
		orderMap.put("bookingQty", mallOrder.getGoodsquantity());
		orderMap.put("needBalloon", mallOrder.getNeedballoon());
		orderMap.put("needDesk", mallOrder.getNeeddesk());
		orderMap.put("needClean", mallOrder.getNeedclean());
		orderMap.put("needInvoice", mallOrder.getNeedinvoice());
		orderMap.put("needRoom", mallOrder.getNeedroom());
		orderMap.put("needMaterial",mallOrder.getNeedmaterial());
		orderMap.put("balloonFee", NumberUtil.round(mallOrder.getBalloonfee(), 2).doubleValue());
		orderMap.put("deskFee", NumberUtil.round(mallOrder.getDeskfee(), 2).doubleValue());
		orderMap.put("cleanFee", NumberUtil.round(mallOrder.getCleanfee(), 2).doubleValue());
		//菜品合计也使用饭店佣金
		orderMap.put("dishAmount", NumberUtil.round(mallOrder.getShopamount(), 2).doubleValue());
		orderMap.put("serviceAmount", NumberUtil.round(mallOrder.getServiceamount(), 2).doubleValue());

		//上门宴业务没有分销佣金
		orderMap.put("serviceOrderSourceId", mallOrder.getId());
		orderMap.put("serviceOrderRemark", mallOrder.getNote());
		orderMap.put("diningWay",mallOrder.getDiningway());
		orderMap.put("checkInDate",mallOrder.getCheckindate());
		orderMap.put("livingDate",mallOrder.getLivingdate());
		orderMap.put("orderType",mallOrder.getOrdertype());
		//针对即点即吃
		if(StrUtil.equals("Y",mallOrder.getEattoday())){
			orderMap.put("bookingType","eatImmediate");
		}

		//封装订单明细行
		List<Map<String, Object>> orderDetails = CollectionUtil.newArrayList();
		MallOrderDetail queryDto = new MallOrderDetail();
		queryDto.setOrderId(mallOrder.getId());
		List<MallOrderDetail> orderDetailList = orderDetailService.selectMallOrderDetailList(queryDto);
		for (MallOrderDetail detail : orderDetailList) {
			Map<String, Object> detailMap = new HashMap<>();
			detailMap.put("defaultImage", ImageUtils.filterFileName(detail.getDefaultimage(),microImageUrl));
			detailMap.put("goodsName", detail.getGoodsname());
			detailMap.put("goodsPrice", detail.getPrice());
			detailMap.put("productNo", detail.getProductno());
			detailMap.put("quantity", detail.getQuantity());
			detailMap.put("specs", detail.getSpecs());
			detailMap.put("oriOrderId", mallOrder.getId());
			detailMap.put("unitPrice", detail.getUnitprice());
			orderDetails.add(detailMap);
			if(StrUtil.isNotEmpty(detail.getDishlist())){
				orderMap.put("serviceOrderContent", detail.getDishlist());
			}
		}
		orderMap.put("orderDetails", orderDetails);
		log.info("传输订单字符串：" + JSONUtil.toJsonStr(orderMap));
		String responseStr = HttpRequest.post(appBaseUrl+ LinkUrl.SHARE_BANQUET_URL).body(JSONUtil.toJsonStr(orderMap)).execute().body();
		log.info("返回字符串"+responseStr);
		ResponseDto responseDto = JSONUtil.toBean(responseStr, ResponseDto.class);
		if (responseDto.isHasError()) {
			throw new RuntimeException(responseDto.getMessage());
		}
	}
}
